<template>
  <div class="app-container">
    <div class="none2-border3 mainbox ">
      <div class="gen_edit">
        <el-form ref="sendForm" :model="form" :rules="rules"
                 label-width="92px" style="margin:32px 0">
          <el-row :gutter="40">
            <el-col :span="24">
              <div class="btnbox">
                <el-button
                  class="filter-item"
                  @click="cancel"
                >取消
                </el-button>
                <el-button
                  type="primary"
                  class="filter-item"
                  @click="submit"
                >保存并发送
                </el-button>
              </div>
            </el-col>
            <el-col :span="8">
              <el-form-item label="模板名称" prop="templateName">
                <el-input v-model="form.templateName" disabled class="limit"
                          placeholder="请输入模板名称" show-word-limit maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="消息类型" prop="typeName">
                <el-select v-model="typeObj" value-key="typeId" placeholder="请选择消息类型"
                           disabled style="width:100%;" @change="selectType()">
                  <el-option
                    v-for="item in messageTypeList"
                    :key="item.typeId"
                    :label="item.typeName"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="优先级" prop="priorityLevel">
                <el-select v-model="form.priorityLevel" disabled placeholder="请选择优先级"
                           style="width:100%;">
                  <el-option
                    v-for="dict in dict.type.classifyLevel"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发送渠道" prop="channelObj">
                <el-select v-model="channelObj" value-key="channelId" multiple
                           disabled placeholder="请选择发送渠道" style="width:100%;">
                  <el-option
                    v-for="item in channelList"
                    :key="item.channelId"
                    :label="item.channelName"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="模板标题" prop="templateTitle">
                <el-input v-model.trim="form.templateTitle" disabled class="limit"
                          show-word-limit placeholder="请输入模板标题" maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="模板内容" prop="templateContent">
                <el-input v-model.trim="form.templateContent" disabled class="limit"
                          type="textarea" show-word-limit placeholder="请输入模板内容"
                          maxlength="100" :rows="4" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="接收方" prop="receivePerson">
                <el-col :span="8">
                  <el-form-item v-if="channelType.includes(3)" label="用户账号" prop="accountReceiver">
                    <el-input v-model.trim="form.accountReceiver" class="limit" show-word-limit
                              placeholder="请输入用户账号" maxlength="20" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item v-if="channelType.includes(1)" label="用户手机号" prop="phoneReceiver">
                    <el-input v-model.trim="form.phoneReceiver" class="limit" show-word-limit
                              placeholder="请输入用户手机号" maxlength="11" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item v-if="channelType.includes(2)" label="用户邮箱" prop="emailReceiver">
                    <el-input v-model.trim="form.emailReceiver" class="limit" show-word-limit
                              placeholder="请输入用户邮箱" maxlength="50" />
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="消息标题" prop="messageTitle">
                <el-input
                  v-model.trim="form.messageTitle"
                  class="limit"
                  type="textarea"
                  :rows="4"
                  show-word-limit
                  placeholder="请输入消息标题，json格式，如：
{
  &quot;name&quot;:&quot;XXX&quot;
}"
                  maxlength="80"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="消息内容" prop="messageParams">
                <el-input
                  v-model.trim="form.messageParams"
                  class="limit"
                  type="textarea"
                  show-word-limit
                  placeholder="请输入消息内容，json格式，如：
{
  &quot;day&quot;:&quot;15&quot;
}"
                  maxlength="200"
                  :rows="4"
                />
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { getTemplate, sendTemplate, listMessageType, getChannelListByTypeCode } from '@/framework/api/template/Template'
import {
  checkEmail,
  checkUserName,
  checkPhone
} from '@/framework/utils/validate'

export default {
  dicts: ['messageType', 'classifyLevel', 'wayType', 'receivePerson'],
  // components: {
  //   selectPerson
  // },
  data() {
    return {
      infoObj: {},
      dataSourceList: [],
      tableList: [],
      channelList: [],
      messageTypeList: [],
      form: {},
      typeObj: {},
      channelObj: [],
      channelType: [],
      templateId: '',
      rules: {
        // messageTitle: [
        //   { required: true, message: '请输入消息标题', trigger: 'blur' }
        // ],
        messageParams: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ],
        accountReceiver: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入账号'))
            } else if (!checkUserName(value)) {
              callback(new Error('账号长度1-20字母、数字组成（不区分大小写）'))
            } else {
              callback()
            }
          }
        }],
        emailReceiver: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入邮箱'))
            } else if (!checkEmail(value)) {
              callback(new Error('邮箱格式错误'))
            } else callback()
          }
        }],
        phoneReceiver: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入手机号'))
            } else if (!checkPhone(value)) {
              callback(new Error('手机号格式错误'))
            } else callback()
          }
        }]
      }
    }
  },
  computed: {
    visitedViews() {
      return this.$store.state.tagsView.visitedViews
    }
  },
  mounted() {
    this.getTypeList()
  },
  methods: {
    // 获取消息类型列表
    getTypeList() {
      listMessageType().then((res) => {
        this.messageTypeList = res.data
        if (this.$route.query.templateId) {
          this.templateId = this.$route.query.templateId
          this.getDetail(this.templateId)
        }
      })
    },
    // 获取详情
    getDetail(templateId) {
      getTemplate(templateId).then((res) => {
        this.form = res.data
        const temp = this.messageTypeList.filter((item) => {
          return item.typeId === this.form.typeId
        })
        if (temp.length) {
          this.typeObj = temp[0]
          this.getChannelId(this.typeObj.typeCode)
        }
      })
    },
    // 由typeCode获取渠道
    getChannelId(val) {
      getChannelListByTypeCode(val).then((res) => {
        this.channelList = res.data
        this.channelObj = this.channelList.map((item) => {
          return item
        })
        this.form.channelId = this.channelObj.map((item) => {
          return item.channelId
        }).join(',')
        this.channelType = this.channelObj.map((item) => {
          return item.channelType
        })
      })
    },
    submit() {
      this.$refs['sendForm'].validate((valid) => {
        if (valid) {
          sendTemplate(this.form).then((res) => {
            this.$dtModal.msgSuccess('发送成功')
            this.form = {}
            // this.$router.push('/template')
            this.cancel()
          })
        }
      })
    },
    cancel() {
      const nowtag = this.visitedViews.filter((item) => {
        if (item.path === this.$route.path) return item
      })
      this.$store.dispatch('tagsView/delView', nowtag[0])
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="scss" scoped>
.gen_edit{
    height: 100%;
    flex: 1;
    background: #fff;
    padding: 0 20px 20px;
    border-radius: 4px;
    box-shadow: 0px 4px 8px 2px rgb(0 0 0 / 4%), 0px 2px 6px 0px rgb(0 0 0 / 6%), 0px 0px 4px 0px rgb(0 0 0 / 8%);
}
.columnsform .el-form-item{
  margin-bottom:0!important;
}
.btnbox{
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 22px;
}
</style>
